#!/bin/bash
set -e

TMP=${TMP:-/tmp/work}
LOG=${LOG:-$HOME/logs/stage1}
SRC=${SRC:-$LFS/sources}

name=glibc
version=2.33
gcc_ver=10.2.0

rm -fr $TMP
mkdir -pv $TMP $LOG

tar xf $SRC/$name-$version.tar.xz -C $TMP

{ time \
   {
    
    cd $TMP/$name-$version

    case $(uname -m) in
        i?86)   ln -sfv ld-linux.so.2 $LFS/lib/ld-lsb.so.3
        ;;
        x86_64) ln -sfv ../lib/ld-linux-x86-64.so.2 $LFS/lib64
                ln -sfv ../lib/ld-linux-x86-64.so.2 $LFS/lib64/ld-lsb-x86-64.so.3
        ;;
    esac

    patch -Np1 -i $SRC/$name-$version-fhs-1.patch

    mkdir -v build
    cd       build

    ../configure                            \
        --prefix=/usr                      \
        --host=$LFS_TGT                    \
        --build=$(../scripts/config.guess) \
        --enable-kernel=3.2                \
        --with-headers=$LFS/usr/include    \
        libc_cv_slibdir=/lib

    make
    
    make DESTDIR=$LFS install

    echo 'int main(){}' > dummy.c
    $LFS_TGT-gcc dummy.c
    readelf -l a.out | grep '/ld-linux'

    rm -v dummy.c a.out
    
    $LFS/tools/libexec/gcc/$LFS_TGT/$gcc_ver/install-tools/mkheaders

    }
} 2>&1 | tee $name.log

[ $PIPESTATUS = 0 ] && mv $name.log $LOG || exit $PIPESTATUS

rm -fr $TMP
